<?php
/*
 * Sample 3 shows how detect the exit status of forked child process.
 */
use IFeng\Process\ChildProcess;
use IFeng\Process\Process;
require_once dirname(__FILE__).'/common.inc.php';
mark('SAMPLE 3 START');

class Sample3 implements IFeng\Process\Runnable {
	/**
	 * @var callback
	 */
	private $_onExit;
	/**
	 * @param callback $onExit
	 */
	public function __construct($onExit) {
		$this->_onExit = $onExit;
	}
	/**
	 * @see IFeng\Process\Runnable::run()
	 */
	public function run() {
		mark('---CHILD START');
		$code = call_user_func($this->_onExit);
		mark('---CHILD END');
		return $code;
	}
}

$callbacks = array();
$callbacks['Return code is 0'] = function() {return 0;};
$callbacks['Return code is -1'] = function() {return -1;};
$callbacks['Return code is 1'] = function() {return 1;};
$callbacks['Not exit'] = function() {sleep(2);};
$callbacks['SIGKILL'] = function() {sleep(3);};
$callbacks['SIGTERM'] = function() {sleep(3);};
$callbacks['SIGTSTP'] = function() {sleep(1);sleep(3);};

$children = array();
foreach ($callbacks as $message => $callback) {
	mark("RUN['$message']");
	$children[$message] = Process::current()->fork(new Sample3($callback));
}

$pid = $children['SIGKILL']->getPid();
$result = posix_kill($pid, SIGKILL);
mark("posix_kill($pid, ".SIGKILL."); returns $result");

$pid = $children['SIGTSTP']->getPid();
$result = posix_kill($pid, SIGTSTP);
mark("posix_kill($pid, ".SIGTSTP."); returns $result");

$pid = $children['SIGTERM']->getPid();
$result = posix_kill($pid, SIGTERM);
mark("posix_kill($pid, ".SIGTERM."); returns $result");

sleep(2);

mark('CHECKING...');
function checkProcess(ChildProcess $process) {
	$status = $process->getStatus();
	echo ' - code: '.$status->getCode()."\n";
	echo ' - isNormalExit: '.($status->isNormalExit()? 'TRUE' : 'FALSE')."\n";
	echo ' - isSignaled: '.($status->isSignaled()? 'TRUE' : 'FALSE')."\n";
	echo ' - isStopped: '.($status->isStopped()? 'TRUE' : 'FALSE')."\n";
	echo ' - getExitCode: '.$status->getExitCode()."\n";
	echo ' - getTerminationSignal: '.$status->getTerminationSignal()."\n";
	echo ' - getStopSignal: '.$status->getStopSignal()."\n";
}
foreach ($children as $message=>$process) {
	echo "$message :\n";
	checkProcess($process);
}

mark('SAMPLE 2 END');